using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Terra.Core.Middleware.Logging
{
    /// <summary>
    /// 请求日志中间件
    /// </summary>
    public class RequestLoggingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<RequestLoggingMiddleware> _logger;

        public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var stopwatch = Stopwatch.StartNew();
            var requestPath = context.Request.Path;
            var method = context.Request.Method;

            try
            {
                _logger.LogInformation("开始处理请求 {Method} {Path}", method, requestPath);
                await _next(context);
                stopwatch.Stop();

                _logger.LogInformation(
                    "请求处理完成 {Method} {Path} - 状态码: {StatusCode}, 耗时: {ElapsedMilliseconds}ms",
                    method,
                    requestPath,
                    context.Response.StatusCode,
                    stopwatch.ElapsedMilliseconds);
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                _logger.LogError(
                    ex,
                    "请求处理异常 {Method} {Path} - 耗时: {ElapsedMilliseconds}ms",
                    method,
                    requestPath,
                    stopwatch.ElapsedMilliseconds);
                throw;
            }
        }
    }
}